#pragma once

#include <string>
#include <memory>
#include <functional>
#include "order.h"

namespace hft {

// 执行引擎接口类
class ExecutionEngine {
public:
    virtual ~ExecutionEngine() = default;

    // 发送订单到交易所
    virtual bool sendOrder(const Order& order) = 0;
    
    // 修改订单
    virtual bool modifyOrder(const Order& order) = 0;
    
    // 取消订单
    virtual bool cancelOrder(const Order& order) = 0;
    
    // 设置订单状态回调
    virtual void setOrderCallback(std::function<void(const Order&)> callback) = 0;
    
    // 设置成交回调
    virtual void setTradeCallback(std::function<void(const Trade&)> callback) = 0;
    
    // 连接到交易所
    virtual bool connect() = 0;
    
    // 断开与交易所的连接
    virtual void disconnect() = 0;
    
    // 检查连接状态
    virtual bool isConnected() const = 0;
    
    // 获取交易所时间
    virtual int64_t getExchangeTime() const = 0;
};

// 模拟执行引擎类
class SimulatedExecutionEngine : public ExecutionEngine {
public:
    SimulatedExecutionEngine();
    ~SimulatedExecutionEngine() override = default;

    // 实现ExecutionEngine接口
    bool sendOrder(const Order& order) override;
    bool modifyOrder(const Order& order) override;
    bool cancelOrder(const Order& order) override;
    void setOrderCallback(std::function<void(const Order&)> callback) override;
    void setTradeCallback(std::function<void(const Trade&)> callback) override;
    bool connect() override;
    void disconnect() override;
    bool isConnected() const override;
    int64_t getExchangeTime() const override;

    // 模拟市场价格更新
    void updateMarketPrice(const std::string& symbol, double price);
    
    // 设置模拟延迟（毫秒）
    void setSimulatedLatency(int latency_ms);
    
    // 设置成交概率（0-1）
    void setFillProbability(double probability);

private:
    // 处理订单匹配
    void processOrderMatch(Order& order);
    
    // 生成模拟成交
    void generateSimulatedTrade(Order& order, int volume, double price);

private:
    std::function<void(const Order&)> order_callback_;
    std::function<void(const Trade&)> trade_callback_;
    std::unordered_map<std::string, double> market_prices_;
    bool is_connected_;
    int simulated_latency_ms_;
    double fill_probability_;
    uint64_t next_trade_id_;
};

} // namespace hft